//
//  REditNoteViewController.m
//  Riji
//
//  Created by  on 2022/8/19.
//

#import "REditNoteViewController.h"
#import "RImgOlineViewController.h"
#import "RPhotoCell.h"
#import "RLocation.h"
@interface REditNoteViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
@property (strong, nonatomic) IBOutlet UITextView *input;
@property (strong, nonatomic) IBOutlet UICollectionView *colletionView;
@property (strong, nonatomic) IBOutlet UIButton *wordNumBtn;
@property (strong, nonatomic) IBOutlet UIButton *addressBtn;
@property (strong, nonatomic) IBOutlet UIButton *weatherBtn;
@property (strong, nonatomic) IBOutlet UIButton *feelingBtn;
@property (nonatomic, strong) NSMutableArray *imgs;
@property (nonatomic, strong) UIButton *rightBtn;
@end

@implementation REditNoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self updateUI];
    [self addtap];
}
- (void)initUI{
    self.title = LS(@"写日记");
    self.imgs = [NSMutableArray array];
    [self.colletionView registerNib:[RPhotoCell nib] forCellWithReuseIdentifier:[RPhotoCell ID]];
    [self.backBtn setImage:[UIImage imageNamed:@"叉"] forState:UIControlStateNormal];
    self.rightBtn.hidden = NO;
}

- (UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, StuBarHight + 5, 40, 40)];
        [_rightBtn setImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(actionForRightBtn:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    }
    return _rightBtn;
}
- (void)updateUI{
    if (self.model != nil) {
        self.input.text = self.model.content;
        [self.addressBtn setTitle:self.model.address forState:UIControlStateNormal];
        [self.weatherBtn setTitle:self.model.weather forState:UIControlStateNormal];
        [self.wordNumBtn setTitle:self.model.wordNum forState:UIControlStateNormal];
        self.imgs = [NSMutableArray arrayWithArray:self.model.data];
        [self.colletionView reloadData];
    }
}
#pragma mark - 叉叉按钮方法
-(void)backBtnAction{
    RPopAlertViewController *vc = [RPopAlertViewController new];
    vc.msgLbl.text = LS(@"确认要退出编辑吗？退出后内容将不保存！");
    vc.enterBlock = ^(NSString * _Nonnull string) {
        [super backBtnAction];
    };
    [self presentViewController:vc animated:NO completion:nil];
}
#pragma mark - 勾勾按钮方法
-(void)actionForRightBtn:(UIButton*)sender{
    if (self.input.isFirstResponder) {
        [self.input endEditing:YES];
    }
    if (self.input.text.length <= 0) {
        return [RLHud msg:LS(@"至少说点什么吧?")];
    }
    if (self.model == nil) {
        self.model = [RNoteModel new];
        self.model.stamp = [[NSDate currentTimeStamp:@"yyyy-MM-dd HH:mm"]intValue];
    }
    NSDateComponents *com = [NSDate dateOfStamp:self.model.stamp];
    self.model.ID = APP.user.ID;
    self.model.year = [NSString stringWithFormat:@"%d",(int)com.year];
    self.model.month = [NSString stringWithFormat:@"%d",(int)com.month];
    self.model.day = [NSString stringWithFormat:@"%d",(int)com.day];
    self.model.week = [NSString stringWithFormat:@"%d",(int)com.weekday];
    self.model.time = [NSDate transToDate:@"HH:mm" :self.model.stamp];
    self.model.content = self.input.text;
    self.model.address = self.addressBtn.currentTitle;
    self.model.weather = self.weatherBtn.currentTitle;
    self.model.wordNum = self.wordNumBtn.currentTitle;
    self.model.feeling = self.feelingBtn.currentTitle;
    self.model.data = self.imgs;
    self.model.remove = NO;
    [RLHud startHud:LS(@"正在保存，请稍后...")];
    [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:notifyNoteUpdate object:nil];
            [RLHud startHud:LS(@"保存成功") stopTime:1 handle:^{
                [super backBtnAction];
            }];
        });
    }];
}
#pragma mark - 定位/天气/心情/补充说明按钮事件
- (IBAction)actionForBtn:(UIButton *)sender {
    WS(self)
    if (sender.tag == 201) {
        RDeletePopViewController *vc = [RDeletePopViewController new];
        vc.titles = @[@"自动定位",@"自定义地点",@"清除定位数据"];
        vc.viewBottom.constant = SCREEN_HEIGHT / 2 - vc.titles.count * 3 / 2;
        vc.deleteBlock = ^(NSString * title) {
            if ([title isEqualToString:@"自动定位"]) {
                [sender setTitle:LS(@"定位中...") forState:UIControlStateNormal];
                APP.location.location = ^(NSString * _Nonnull address) {
                    sender.selected = YES;
                    [sender setTitle:address forState:UIControlStateNormal];
                };
                APP.location.cityWeather = ^(NSString * _Nonnull weather) {
                    NSLog(@"当前位置的天气是     %@",weather);
                    [self.weatherBtn setTitle:LS(weather) forState:UIControlStateNormal];
                    [self.weatherBtn setTitleColor:[UIColor colorWithHexString:@"#2F88EE"] forState:UIControlStateNormal];
                };
                
            }else if ([title isEqualToString:@"自定义地点"]){
                RPopAlertViewController *vc = [RPopAlertViewController new];
                vc.input.hidden = NO;
                [vc.enterBtn setTitleColor:[UIColor colorWithHexString:@"#2F88EE"] forState:UIControlStateNormal];
                [vc.cancelBtn setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
                vc.enterBlock = ^(NSString * _Nonnull nickname) {
                    sender.selected = nickname.length > 0;
                    [sender setTitle:nickname.length > 0 ? nickname : LS(@"获取定位") forState:UIControlStateNormal];
                };
                [weakself presentViewController:vc animated:NO completion:nil];
            }else if ([title isEqualToString:@"清除定位数据"]){
                sender.selected = NO;
                [sender setTitle:LS(@"获取定位") forState:UIControlStateNormal];
            }
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 202){
        [weakself sheet:nil msg:nil sheet:@[@"晴",@"多云",@"阴",@"雨",@"雷阵雨",@"雪",@"大风"] sheetBlock:^(int index, NSString *sheetTitle) {
            [sender setTitle:LS(sheetTitle) forState:UIControlStateNormal];
            [sender setTitleColor:[UIColor colorWithHexString:@"#2F88EE"] forState:UIControlStateNormal];
        }];
    }else if (sender.tag == 203){
        REMOViewController *vc = [REMOViewController new];
        vc.emoBlock = ^(NSString * _Nonnull emo) {
            [sender setTitle:emo forState:UIControlStateNormal];
            [sender setTitleColor:[UIColor colorWithHexString:@"#2F88EE"] forState:UIControlStateNormal];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 204){
        
    }
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    [self.imgs addObject:imageData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self.colletionView reloadData];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    [self.wordNumBtn setTitle:[NSString stringWithFormat:LS(@"%d字"),(int)textView.text.length] forState:UIControlStateNormal];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.imgs.count + 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    RPhotoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[RPhotoCell ID] forIndexPath:indexPath];
    cell.selectBtn.hidden = NO;
    [cell.selectBtn setImage:[UIImage imageNamed:@"叉"] forState:UIControlStateNormal];
    if (indexPath.row == self.imgs.count) {
        cell.img.image = [UIImage imageNamed:@"拍照"];
        cell.selectBtn.hidden = YES;
    }else{
        cell.img.image = [UIImage imageWithData:self.imgs[indexPath.row]];
    }
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.imgs.count) {
        [self.view endEditing:YES];
        WS(self)
        [weakself sheet:nil msg:nil sheet:@[@"相机",@"相簿",@"图库"] sheetBlock:^(int index, NSString *sheetTitle) {
            if ([sheetTitle isEqualToString:@"图库"]) {
                RImgOlineViewController *vc = [RImgOlineViewController new];
                vc.resultBlock = ^(NSArray * _Nonnull array) {
                    for (KImage *model in array) {
                        [weakself.imgs addObject:model.data];
                    }
                    [collectionView reloadData];
                };
                return [self.navigationController pushViewController:vc animated:YES];
            }
            UIImagePickerController *vc = [[UIImagePickerController alloc] init];
            vc.delegate = self;
            vc.allowsEditing = YES;
            vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [weakself presentViewController:vc animated:YES completion:nil];
        }];
    }else{
        RPhotoCell *cell = (RPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        if (cell.selectBtn.hidden == NO) {
            [self.imgs removeObjectAtIndex:indexPath.row];
            [collectionView reloadData];
        }
    }
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 15 * 6) / 5;
    return  CGSizeMake(w,w);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(0, 15, 0, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

@end
